package com.che.libcommon.ui;

import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;

public class BaseActivity extends AppCompatActivity implements ICloseWatcher {

  private boolean statusBarFit = false;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(onlyPortrait()){
      try {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      }catch (Throwable e){
        e.printStackTrace();
      }
    }
  }

  @Override
  public void setContentView(int layoutResID) {
    super.setContentView(layoutResID);
    if (autoHackStatusBar()){
      setTranslucentStatus();
    }
  }

  @Override
  public void setContentView(View view) {
    super.setContentView(view);
    if (autoHackStatusBar()){
      setTranslucentStatus();
    }
  }

  protected void setTitle(){

  }

  protected boolean onlyPortrait(){
    return true;
  }

  protected boolean autoHackStatusBar(){
    return true;
  }


  protected void setTranslucentStatus() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      if (statusBarFit){
        return;
      }
      View contentView = findViewById(android.R.id.content);

      if (contentView instanceof ViewGroup && ((ViewGroup) contentView).getChildCount() >0){
        View childAt = ((ViewGroup) contentView).getChildAt(0);

        if (childAt != null){
          childAt.setFitsSystemWindows(true);
          statusBarFit = true;
        }

      }

    }
  }

  protected void removeTranslucentStatus(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      if (!statusBarFit){
        return;
      }

      View contentView = findViewById(android.R.id.content);

      if (contentView instanceof ViewGroup && ((ViewGroup) contentView).getChildCount() >0){
        View childAt = ((ViewGroup) contentView).getChildAt(0);

        if (childAt != null){
          childAt.setFitsSystemWindows(false);
          statusBarFit = false;
        }

      }

    }
  }

  @Override
  public void finishView() {
    finish();
  }
}
